import React from 'react'
import $ from 'jquery'
import _ from 'underscore'
import View from 'lib/View.jsx'
import Layout from '../common/layout.jsx'
import Card from 'lib/components/card.jsx'
import ChartWidget from 'lib/components/ChartWidget.jsx'
import GridWidget from 'lib/components/GridWidget.jsx'
import Select2 from 'lib/components/Select.jsx'
import Tab from 'lib/components/tab.jsx'
import DefaultNoDataElement from 'lib/util/defaultNoDataElement.jsx'
import MainScope from './MainScope.es6'
import DetailModal from './DetailModal.jsx'
import dispatcher from 'lib/dispatcher'
import addWidgetMixin from '../common/NewDashboardWidget.jsx'

export default class MainView extends View{
  constructor(props){
    super(props)
    this.submit = this.submit.bind(this)
    this.indicatorChange = this.indicatorChange.bind(this)
    this.clickPoint = this.clickPoint.bind(this)
  }
  submit(){
    var indicatorValue = this.refs.indicator.state.values.map((o)=> o.value)[0]
      , dimValue = this.refs.dim.state.values.map((o)=> o.value)[0]
    dispatcher.dispatch({
      $type:'submit_conditions',
      params:_.extend({},indicatorValue,{
        classify:dimValue
      },this.getfilterConditionValues(indicatorValue))
    })
  }
  getfilterConditionValues(indicatorValue){
    var condValues = _.chain(this.state.filterConditions).map(function(cond){
      return [cond.key,this.refs[cond.key].state.values.map((o)=> o.value)]
    },this).reduce(function(i,acc){
      var kv = {};
      if(acc[1].length>0){
        if(_.isObject(acc[1][0])){
          kv = _(acc[1]).reduce(function(a,memo){
            return _(a).mapObject((o,k) => o.concat([memo[k]]))
          },_.chain(acc[1][0]).keys().map((k) => [k,[]]).object().value())
        }else{
          kv = _([[acc[0],acc[1]]]).object()
        }
      }else{
        kv = _([[acc[0],'']]).object()
      }
      return _.extend(i,
        kv
      )
    },{}).value()
    condValues.limit = this.refs.limit.state.values.map((o)=> o.value)[0]
    if(this.state.category==='crash'){
      condValues.imsi = $(this.refs.imsi).val()
    }
    if(indicatorValue.urlName==='errorrate'){
      if((condValues.errorCode&&condValues.errorCode.length)||(condValues.statusCode&&condValues.statusCode.length)){
        indicatorValue.errorCode = undefined;
        indicatorValue.statusCode = undefined;
        condValues.codeEq = true
      }else{
        condValues = _.omit(condValues,'errorCode','statusCode')
      }
    }
    return condValues
  }
  indicatorChange(val){
    dispatcher.dispatch({
      $type:'indicator_change',
      category:val.value.category,
      value:val.value
    })
  }
  clickPoint(ev){
    DetailModal.mount({
      pId:ev.point.id,
      name:ev.point.name,
      category:this.state.category,
      params:this.state.params
    })
  }
  render(){
    return (
      <Layout title="组合分析" subtitle="性能指标组合分析" hideVersion={true}>
        <div className="pure-g">
          <div className="pure-u-1 pure-u-lg-1-4">
            <div className="box comb-box">
              <Card title="创建组合分析">
                <Card title="指标">
                  <Select2
                    ref="indicator"
                    options={this.state.indicatorOptions}
                    onChange={this.indicatorChange}
                    value={
                      _(this.state.indicatorOptions).find(
                        (o) => o.value.viewKey === this.state.params.viewKey && o.value.category === this.state.category
                      , this)
                    }
                  />
                </Card>
                <Card title="维度" subtitle="按如下指标进行查看">
                  <Select2
                    ref="dim"
                    options={this.state.dimOptions}
                    value={
                      _(this.state.dimOptions).find(
                        (o) => o.value === this.state.params.classify
                      , this)
                    }
                  />
                </Card>
                <Card title="筛选条件">
                  {
                    this.state.filterConditions.map(function(cond){
                      return (
                        <div className="form-group" key={cond.key}>
                          <label className="control-label">{cond.name}</label>
                          <Select2
                            ref={cond.key}
                            multi={true}
                            options={cond.options}
                            value={
                              _(cond.options).filter(
                                (o) => _.contains(this.state.params[cond.key],_.isObject(o.value)?o.value[cond.key]:o.value)
                              , this)
                            }
                          />
                        </div>
                      )
                    },this)
                  }
                  {
                    this.state.category === 'crash'?(
                      <div className="form-group">
                        <label className="control-label">用户信息（IMSI）</label>
                        <input type="text" ref="imsi" className="input-text" placeholder="请输入..." defaultValue={this.state.params.imsi} />
                      </div>
                    ):null
                  }
                  <div className="form-group">
                    <label className="control-label">TopN</label>
                    <Select2
                      ref="limit"
                      options={this.state.limitOption}
                      value={
                        _.findWhere(this.state.limitOption,{value:this.state.params.limit})
                      }
                    />
                  </div>
                </Card>
                <button className="btn-blue btn-lg btn-block" type="button" onClick={this.submit}>绘制</button>
              </Card>
            </div>
          </div>
          <div className="pure-u-1 pure-u-lg-3-4">
            <div className="box comp-box">
              <Card title="趋势图" extra={
                  this.scope.combAnalysisApi?(
                    <a target="_blank" download={true} className="btn-blue"
                      href={this.scope.combAnalysisApi.lastUrl.replace('.json','.csv')+'?'+$.param(_.extend({
                        anylize:_(this.state.indicatorOptions).find(
                          (o) => o.value.viewKey === this.state.params.viewKey && o.value.category === this.state.category
                        , this).value.exportKey
                      },this.scope.combAnalysisApi.lastParams),true)}
                      >导出</a>
                  ):null

                }>
                <div className="pure-g">
                  <div className="pure-u-1 pure-u-xl-5-12">
                    <div className="box">
                      <Card extra={
                        addWidgetMixin(this.scope.combAnalysisApi,'组合分析',{
                          chartType:'pie'
                        })
                      }>
                        <ChartWidget chartType="pie" store={this.state.pie}/>
                      </Card>
                    </div>
                  </div>
                  <div className="pure-u-1 pure-u-xl-7-12">
                    <div className="box">
                      <Card extra={
                        addWidgetMixin(this.scope.combAnalysisApi,'组合分析')
                      }>
                        <ChartWidget chartType="line" store={this.state.chart}/>
                      </Card>
                    </div>
                  </div>
                  <div className="pure-u-1">
                    <div className="box">
                      <Card>
                        <GridWidget store={this.state.grid} cols={[{
                          title:'维度',
                          key:'name',
                          sortable:true,
                          render:function(fmtVal,rowData){
                            return (
                              <a href="javascript:;" onClick={this.clickPoint.bind(this,{
                                point:{
                                  id:this.state.params.classify==='exceptiontype'?fmtVal:rowData.id,
                                  name:fmtVal
                                }
                              })}>
                                {fmtVal}
                              </a>
                            )
                          }.bind(this)
                        }].concat(this.state.gridCols)}/>
                      </Card>
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          </div>
        </div>
      </Layout>
    )
  }
}
MainView.defaultProps = {
  Scope:MainScope
}
